package com.sjgl.esdn.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgl.esdn.search.domain.MyFile;
import com.sjgl.esdn.search.domain.QueryResult;
import com.sjgl.esdn.search.domain.QueryResultTop;
import com.sjgl.esdn.service.BlogService;
import com.sjgl.esdn.search.utils.ImageUtils;
import com.sjgl.esdn.service.FileService;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class BlogServiceImpl implements BlogService {
    @Resource
    private RestHighLevelClient client;

    @Autowired
    private FileService fileService;

    private static final String ESDN_INDEX = "esdn2";
    private static final Integer Is_Deleted = -1;

    @Override
    public MyFile getMyFileById(String id) throws IOException {
        GetRequest getRequest = new GetRequest(ESDN_INDEX, id);
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        Map<String, Object> resource = getResponse.getSource();
        MyFile myFile = new MyFile();
        myFile.setId(id);
        if(resource==null||resource.isEmpty()){
            return null;
        }
        if (resource.get("fileType").equals(Is_Deleted)) {
            return null;
        }
        myFile.setFileName(resource.get("fileName").toString());
        myFile.setTitleCompletion(resource.get("fileName").toString());
        myFile.setFileIntro(resource.get("fileIntro").toString());

        if (resource.containsKey("fileContent") && resource.get("fileContent") != null) {
            String thisContent=resource.get("fileContent").toString();
            Integer length=thisContent.length()-256>0?256:thisContent.length();
            myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
        } else {
            myFile.setFileContent(null);
        }
        myFile.setFileSuffix(resource.get("fileSuffix").toString());
        String createTime = resource.get("createTime").toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse(createTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        myFile.setCreateTime(date);
        myFile.setFileSuffix(resource.get("fileSuffix").toString());
        myFile.setDownloadNum(Integer.valueOf(resource.get("downloadNum").toString()));
        myFile.setFileType(Integer.valueOf(resource.get("fileType").toString()));
        if (resource.containsKey("previewUrl") && resource.get("previewUrl") != null) {
            myFile.setPreviewUrl(resource.get("previewUrl").toString());
        } else {
            myFile.setPreviewUrl(null);
        }
        return myFile;
    }

    @Override
    public QueryResult getMyFilesByRef(String query, Integer from, Integer size, Long userId) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("fileName", 3).field("fileIntro").field("fileContent");
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.postFilter(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("fileType", Is_Deleted)));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(
                new HighlightBuilder.Field("fileName")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        highlightBuilder.field(
                new HighlightBuilder.Field("fileIntro")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        //searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        JSONObject rawResult = JSONObject.parseObject(searchResponse.toString());
        Integer total = rawResult.getJSONObject("hits").getJSONObject("total").getInteger("value");
        String relation = rawResult.getJSONObject("hits").getJSONObject("total").getString("relation");
        List<MyFile> myFiles = new ArrayList<>();
        MyFile myFile = new MyFile();
        JSONArray hits = rawResult.getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject hit = hits.getJSONObject(i);
            myFile.setId(hit.getString("_id"));

            //权限判断，消去无权限查看的文件
            if(!fileService.canUserLookFile(userId,Long.parseLong(myFile.getId()))){
                continue;
            }

            JSONObject source = hit.getJSONObject("_source");

            myFile.setFileName(source.get("fileName").toString());
            myFile.setTitleCompletion(source.get("fileName").toString());
            myFile.setFileIntro(source.get("fileIntro").toString());
            if (source.containsKey("fileContent") && source.get("fileContent") != null) {
                String thisContent=source.get("fileContent").toString();
                Integer length=thisContent.length()-256>0?256:thisContent.length();
                myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
            } else {
                myFile.setFileContent(null);
            }

            String createTime = source.get("createTime").toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = dateFormat.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            myFile.setCreateTime(date);
            myFile.setFileSuffix(source.get("fileSuffix").toString());
            myFile.setDownloadNum(Integer.valueOf(source.get("downloadNum").toString()));
            myFile.setFileType(Integer.valueOf(source.get("fileType").toString()));
            if (source.containsKey("previewUrl") && source.get("previewUrl") != null) {
                myFile.setPreviewUrl(source.get("previewUrl").toString());
            } else {
                myFile.setPreviewUrl(null);
            }

            if (hit.containsKey("highlight")) {
                JSONObject highlight = hit.getJSONObject("highlight");
                for (String key : highlight.keySet()) {
                    if (key.equals("fileName")) {
                        myFile.setFileName(highlight.getJSONArray("fileName").getString(0));
                    }
                    if (key.equals("fileIntro")) {
                        myFile.setFileIntro(highlight.getJSONArray("fileIntro").getString(0));
                    }
                }
            }

            myFiles.add(myFile);
            myFile = new MyFile();
        }
        QueryResult queryResult = new QueryResult(total, relation, myFiles);

        return queryResult;
    }

    @Override
    public QueryResult getMyFilesByDownload(String query, Integer from, Integer size,Long userId) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("fileName", 3).field("fileIntro").field("fileContent");
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort(new FieldSortBuilder("downloadNum").order(SortOrder.DESC));
        searchSourceBuilder.postFilter(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("fileType", Is_Deleted)));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(
                new HighlightBuilder.Field("fileName")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        highlightBuilder.field(
                new HighlightBuilder.Field("fileIntro")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        //searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        JSONObject rawResult = JSONObject.parseObject(searchResponse.toString());
        Integer total = rawResult.getJSONObject("hits").getJSONObject("total").getInteger("value");
        String relation = rawResult.getJSONObject("hits").getJSONObject("total").getString("relation");
        List<MyFile> myFiles = new ArrayList<>();
        MyFile myFile = new MyFile();
        JSONArray hits = rawResult.getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject hit = hits.getJSONObject(i);
            myFile.setId(hit.getString("_id"));

            //权限判断，消去无权限查看的文件
            if(!fileService.canUserLookFile(userId,Long.parseLong(myFile.getId()))){
                continue;
            }

            JSONObject source = hit.getJSONObject("_source");

            myFile.setFileName(source.get("fileName").toString());
            myFile.setTitleCompletion(source.get("fileName").toString());
            myFile.setFileIntro(source.get("fileIntro").toString());
            if (source.containsKey("fileContent") && source.get("fileContent") != null) {
                String thisContent=source.get("fileContent").toString();
                Integer length=thisContent.length()-256>0?256:thisContent.length();
                myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
            } else {
                myFile.setFileContent(null);
            }

            String createTime = source.get("createTime").toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = dateFormat.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            myFile.setCreateTime(date);
            myFile.setFileSuffix(source.get("fileSuffix").toString());
            myFile.setDownloadNum(Integer.valueOf(source.get("downloadNum").toString()));
            myFile.setFileType(Integer.valueOf(source.get("fileType").toString()));
            if (source.containsKey("previewUrl") && source.get("previewUrl") != null) {
                myFile.setPreviewUrl(source.get("previewUrl").toString());
            } else {
                myFile.setPreviewUrl(null);
            }

            if (hit.containsKey("highlight")) {
                JSONObject highlight = hit.getJSONObject("highlight");
                for (String key : highlight.keySet()) {
                    if (key.equals("fileName")) {
                        myFile.setFileName(highlight.getJSONArray("fileName").getString(0));
                    }
                    if (key.equals("fileIntro")) {
                        myFile.setFileIntro(highlight.getJSONArray("fileIntro").getString(0));
                    }
                }
            }
            myFiles.add(myFile);
            myFile = new MyFile();
        }
        QueryResult queryResult = new QueryResult(total, relation, myFiles);

        return queryResult;
    }

    @Override
    public QueryResult getMyFilesByTime(String query, Integer from, Integer size, Long userId) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("fileName", 3).field("fileIntro").field("fileContent");
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort(new FieldSortBuilder("createTime").order(SortOrder.DESC));
        searchSourceBuilder.postFilter(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("fileType", Is_Deleted)));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(
                new HighlightBuilder.Field("fileName")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        highlightBuilder.field(
                new HighlightBuilder.Field("fileIntro")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        //searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        JSONObject rawResult = JSONObject.parseObject(searchResponse.toString());
        Integer total = rawResult.getJSONObject("hits").getJSONObject("total").getInteger("value");
        String relation = rawResult.getJSONObject("hits").getJSONObject("total").getString("relation");
        List<MyFile> myFiles = new ArrayList<>();
        MyFile myFile = new MyFile();
        JSONArray hits = rawResult.getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject hit = hits.getJSONObject(i);
            myFile.setId(hit.getString("_id"));

            //权限判断，消去无权限查看的文件
            if(!fileService.canUserLookFile(userId,Long.parseLong(myFile.getId()))){
                continue;
            }

            JSONObject source = hit.getJSONObject("_source");

            myFile.setFileName(source.get("fileName").toString());
            myFile.setTitleCompletion(source.get("fileName").toString());
            myFile.setFileIntro(source.get("fileIntro").toString());
            if (source.containsKey("fileContent") && source.get("fileContent") != null) {
                String thisContent=source.get("fileContent").toString();
                Integer length=thisContent.length()-256>0?256:thisContent.length();
                myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
            } else {
                myFile.setFileContent(null);
            }

            String createTime = source.get("createTime").toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = dateFormat.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            myFile.setCreateTime(date);
            myFile.setFileSuffix(source.get("fileSuffix").toString());
            myFile.setDownloadNum(Integer.valueOf(source.get("downloadNum").toString()));
            myFile.setFileType(Integer.valueOf(source.get("fileType").toString()));
            if (source.containsKey("previewUrl") && source.get("previewUrl") != null) {
                myFile.setPreviewUrl(source.get("previewUrl").toString());
            } else {
                myFile.setPreviewUrl(null);
            }

            if (hit.containsKey("highlight")) {
                JSONObject highlight = hit.getJSONObject("highlight");
                for (String key : highlight.keySet()) {
                    if (key.equals("fileName")) {
                        myFile.setFileName(highlight.getJSONArray("fileName").getString(0));
                    }
                    if (key.equals("fileIntro")) {
                        myFile.setFileIntro(highlight.getJSONArray("fileIntro").getString(0));
                    }
                }
            }
            myFiles.add(myFile);
            myFile = new MyFile();
        }
        QueryResult queryResult = new QueryResult(total, relation, myFiles);

        return queryResult;
    }

    @Override
    public QueryResultTop getMyFilesByTop(Integer from, Integer size, Long userId) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RangeQueryBuilder queryBuilder = new RangeQueryBuilder("createTime")
                .gte(dateFormat.format(new Date(System.currentTimeMillis()-86400000*8)));
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.postFilter(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("fileType", Is_Deleted)));
        searchSourceBuilder.sort(new FieldSortBuilder("downloadNum").order(SortOrder.DESC));


        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(
                new HighlightBuilder.Field("fileName")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        highlightBuilder.field(
                new HighlightBuilder.Field("fileIntro")
                        .highlighterType("plain")
                        .preTags("<span style='color:#1a8ade'>")
                        .postTags("</span>"));
        //searchSourceBuilder.highlighter(highlightBuilder);
        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        JSONObject rawResult = JSONObject.parseObject(searchResponse.toString());
        Integer total = rawResult.getJSONObject("hits").getJSONObject("total").getInteger("value");
        String relation = rawResult.getJSONObject("hits").getJSONObject("total").getString("relation");
        List<MyFile> myFiles = new ArrayList<>();
        MyFile myFile = new MyFile();
        JSONArray hits = rawResult.getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject hit = hits.getJSONObject(i);
            myFile.setId(hit.getString("_id"));

            //权限判断，消去无权限查看的文件
            if(!fileService.canUserLookFile(userId,Long.parseLong(myFile.getId()))){
                continue;
            }

            JSONObject source = hit.getJSONObject("_source");

            myFile.setFileName(source.get("fileName").toString());
            myFile.setTitleCompletion(source.get("fileName").toString());
            myFile.setFileIntro(source.get("fileIntro").toString());
            if (source.containsKey("fileContent") && source.get("fileContent") != null) {
                String thisContent=source.get("fileContent").toString();
                Integer length=thisContent.length()-256>0?256:thisContent.length();
                myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
            } else {
                myFile.setFileContent(null);
            }

            String createTime = source.get("createTime").toString();
            Date date = null;
            try {
                date = dateFormat.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            myFile.setCreateTime(date);
            myFile.setFileSuffix(source.get("fileSuffix").toString());
            myFile.setDownloadNum(Integer.valueOf(source.get("downloadNum").toString()));
            myFile.setFileType(Integer.valueOf(source.get("fileType").toString()));
            if (source.containsKey("previewUrl") && source.get("previewUrl") != null) {
                myFile.setPreviewUrl(source.get("previewUrl").toString());
            } else {
                myFile.setPreviewUrl(null);
            }
            if (hit.containsKey("highlight")) {
                JSONObject highlight = hit.getJSONObject("highlight");
                for (String key : highlight.keySet()) {
                    if (key.equals("fileName")) {
                        myFile.setFileName(highlight.getJSONArray("fileName").getString(0));
                    }
                    if (key.equals("fileIntro")) {
                        myFile.setFileIntro(highlight.getJSONArray("fileIntro").getString(0));
                    }
                }
            }
            myFiles.add(myFile);
            myFile = new MyFile();
        }

        List<String> previewList = new ArrayList<>();
        for (MyFile file : myFiles) {
            if(file.getPreviewUrl()!=null && new File(file.getPreviewUrl()).exists()){
                previewList.add(ImageUtils.fileToBase64(file.getPreviewUrl()));
            }
            else{
                previewList.add(ImageUtils.fileToBase64("D:\\ESDN\\files\\preview\\0.jpg"));
            }
        }
        
        QueryResultTop queryResultTop = new QueryResultTop(total, relation, myFiles,previewList);

        return queryResultTop;
    }

    @Override
    public QueryResult getMyFilesMoreLikeThis(String query, Integer from, Integer size, Long userId) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //MoreLikeThisQueryBuilder queryBuilder = new moreLikeThisQuery(query);
        MoreLikeThisQueryBuilder queryBuilder = new MoreLikeThisQueryBuilder(new String[]{"fileName","fileIntro","fileContent"}, new String[]{query},null);
        queryBuilder.minTermFreq(1);
        //MoreLikeThisFieldQueryBuilder queryBuilder = QueryBuilders.moreLikeThisFieldQuery("测试");
        //MultiMatchQueryBuilder queryBuilder = new MultiMatchQueryBuilder(query).field("fileName", 3).field("fileIntro").field("fileContent");
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.sort(new FieldSortBuilder("downloadNum").order(SortOrder.DESC));
        searchSourceBuilder.postFilter(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("fileType", Is_Deleted)));

        searchSourceBuilder.from(from);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        JSONObject rawResult = JSONObject.parseObject(searchResponse.toString());
        Integer total = rawResult.getJSONObject("hits").getJSONObject("total").getInteger("value");
        String relation = rawResult.getJSONObject("hits").getJSONObject("total").getString("relation");
        List<MyFile> myFiles = new ArrayList<>();
        MyFile myFile = new MyFile();
        JSONArray hits = rawResult.getJSONObject("hits").getJSONArray("hits");
        for (int i = 0; i < hits.size(); i++) {
            JSONObject hit = hits.getJSONObject(i);
            myFile.setId(hit.getString("_id"));

            //权限判断，消去无权限查看的文件
            if(!fileService.canUserLookFile(userId,Long.parseLong(myFile.getId()))){
                continue;
            }

            JSONObject source = hit.getJSONObject("_source");

            myFile.setFileName(source.get("fileName").toString());
            myFile.setTitleCompletion(source.get("fileName").toString());
            myFile.setFileIntro(source.get("fileIntro").toString());
            if (source.containsKey("fileContent") && source.get("fileContent") != null) {
                String thisContent=source.get("fileContent").toString();
                Integer length=thisContent.length()-256>0?256:thisContent.length();
                myFile.setFileContent(thisContent.substring(0,length).replace("\r\n\r\n","[图片][图片]"));
            } else {
                myFile.setFileContent(null);
            }

            String createTime = source.get("createTime").toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = dateFormat.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            myFile.setCreateTime(date);
            myFile.setFileSuffix(source.get("fileSuffix").toString());
            myFile.setDownloadNum(Integer.valueOf(source.get("downloadNum").toString()));
            myFile.setFileType(Integer.valueOf(source.get("fileType").toString()));
            if (source.containsKey("previewUrl") && source.get("previewUrl") != null) {
                myFile.setPreviewUrl(source.get("previewUrl").toString());
            } else {
                myFile.setPreviewUrl(null);
            }

            myFiles.add(myFile);
            myFile = new MyFile();
        }
        QueryResult queryResult = new QueryResult(total, relation, myFiles);

        return queryResult;
    }

    @Override
    public List<String> getSuggestion(String text) throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESDN_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        CompletionSuggestionBuilder completionSuggestion =
                SuggestBuilders.completionSuggestion("titleCompletion").text(text);
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("completion-suggest", completionSuggestion);
        searchSourceBuilder.suggest(suggestBuilder);
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        List<String> suggestions = new ArrayList<>();
        CompletionSuggestion suggest = searchResponse.getSuggest().getSuggestion("completion-suggest");
        for (CompletionSuggestion.Entry entry : suggest.getEntries()) {
            for (CompletionSuggestion.Entry.Option option : entry) {
                String suggestText = option.getText().string();
                suggestions.add(suggestText);
            }
        }

        return suggestions;
    }

}
